package com.ontheroad.controller;

import com.ontheroad.core.web.BaseController;
import com.ontheroad.qiniu.service.FileService;
import com.ontheroad.qiniu.service.QiniuyunService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 文件上传
 */
@Controller
@RequestMapping(value = "/file")
public class FileController extends BaseController {
    Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private FileService fileService;

    @RequestMapping(value = "upload")
    @ResponseBody
    public Map<String, Object> upload(HttpServletRequest request, MultipartFile upfile) throws IOException {
        //{"state": "SUCCESS","title": "20170303_1488502564030022030.jpg","original": "joinplan1.jpg","type": ".jpg","url": "/static/upload/file/20170303_1488502564030022030.jpg","size": "38928"}
        Map<String, Object> reMap = new HashMap<>();
        String url = fileService.upload(upfile.getBytes());
        if (url != null) {
            reMap.put("state", "SUCCESS");
            reMap.put("url", url);
            reMap.put("type", url.replaceAll(".+(\\.\\w{2,3})$", "$1"));
            reMap.put("size", upfile.getSize());
        } else {
            reMap.put("state", "FAILD");
        }
        return reMap;
    }
}
